using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UI_Dialogue : MonoBehaviour
{
    private UI uI;
    [SerializeField] private Image _playerImage;
    [SerializeField] private Image _npcImage;
    [SerializeField] private TextMeshProUGUI _dialogueTMP;
    [SerializeField] private float _charInputInterval;
    private DialogueDataBase _curentDialogueDataSO;
    private Coroutine _dialogueTextInputCo;
    private int _dialogueIndex;
    private string _currentDialogueText;
    private Action _callBackInEndOfDialogue;
    private void Awake()
    {
        uI = GetComponentInParent<UI>();
    }
    public void SetupDialogueUI(DialogueDataBase curentDialogueDataSO, Action callBackInEndOfDialogue)
    {
        _dialogueIndex = 0;
        _callBackInEndOfDialogue = callBackInEndOfDialogue;
        _curentDialogueDataSO = curentDialogueDataSO;

        UpdateDialogue();
    }
    public void DialogueInteraction()
    {
        if (_curentDialogueDataSO == null)
        {
            Debug.Log("对话数据为空");
            return;
        }
        if (_dialogueTextInputCo != null)
        {
            //补全对话内容
            CompleteText(_currentDialogueText);
            return;
        }
        UpdateDialogue();
    }

    private void UpdateDialogue()
    {
        if (_dialogueIndex == _curentDialogueDataSO.dialogueDatas.Length)
        {
            ExitDialogue();
            return;
        }
        DialogueData dialogueData = _curentDialogueDataSO.GetDialogueText(_dialogueIndex);
        _currentDialogueText = dialogueData.dialogueText;

        if (dialogueData.dialogueRole == DialogueRole.Player)
        {
            _playerImage.enabled = true;
            _npcImage.enabled = false;
            _playerImage.sprite = dialogueData.dialogueRoleSprite;
        }
        else
        {
            _playerImage.enabled = false;
            _npcImage.enabled = true;
            _npcImage.sprite = dialogueData.dialogueRoleSprite;
        }
        _dialogueTextInputCo = StartCoroutine(TypeTextCo(_currentDialogueText));

        _dialogueIndex++;
    }

    //补全对话内容
    private void CompleteText(string lineText)
    {
        StopCoroutine(_dialogueTextInputCo);
        _dialogueTextInputCo = null;

        _dialogueTMP.text = lineText;
    }

    private IEnumerator TypeTextCo(string lineText)
    {
        _dialogueTMP.text = "";

        foreach (var @char in lineText)
        {
            _dialogueTMP.text += @char;
            yield return new WaitForSeconds(_charInputInterval);
        }

        _dialogueTMP.text = lineText;

        _dialogueTextInputCo = null;
    }
    
    private void ExitDialogue()
    {
        gameObject.SetActive(false);

        uI.EnableUIInput(false);
        
        _callBackInEndOfDialogue?.Invoke();
    }
}
